package com.longy.gulimall.product.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@Slf4j
@RequestMapping("/api/logs")
public class LogLevelController {

    private RestTemplate restTemplate;

    @Autowired
    public void LoggingController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @PostMapping("/set-level")
    public ResponseEntity<String> setLogLevel(@RequestParam String loggerName, @RequestParam String level) {
        String url = "/actuator/loggers/" + loggerName;
        String body = "{\"configuredLevel\":\"" + level + "\"}";

        HttpEntity<String> request = new HttpEntity<>(body);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);

        return response;
    }

    @GetMapping("/testLog")
    public String testLog() {
        log.debug("这是一个debug日志...");
        log.info("这是一个info日志...");
        log.error("这是一个error日志...");
        return "test log";
    }

    public static void main(String[] args) {
        ThreadPoolTaskExecutor poolExecutor = new ThreadPoolTaskExecutor();
        poolExecutor.setCorePoolSize(10);
        poolExecutor.setMaxPoolSize(50);
        poolExecutor.setQueueCapacity(100);
        poolExecutor.setKeepAliveSeconds(60);
        poolExecutor.setThreadNamePrefix("optimized-pool-");
        poolExecutor.setAllowCoreThreadTimeOut(true);
        poolExecutor.setWaitForTasksToCompleteOnShutdown(true);
        poolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        poolExecutor.initialize();

        AtomicInteger completed = new AtomicInteger(0);
        AtomicInteger rejected = new AtomicInteger(0);

        for (int i = 0; i < 2000; i++) {
            try {
                poolExecutor.submit(() -> {
                    Date date = new Date();
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
                    System.out.printf("%s 完成任务 %d/%d%n",
                            format, completed.incrementAndGet(), 2000);
                });
            } catch (RejectedExecutionException e) {
                System.err.println("任务被拒绝：" + e.getMessage());
                rejected.incrementAndGet();
            }
        }

        // 监控线程
        new Thread(() -> {
            while (true) {
                System.out.printf("活跃线程: %d, 队列大小: %d, 已完成: %d, 被拒绝: %d%n",
                        poolExecutor.getActiveCount(),
                        poolExecutor.getKeepAliveSeconds(),
                        completed.get(),
                        rejected.get());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }).start();

        // 优雅关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("关闭线程池...");
            poolExecutor.shutdown();
            try {
                    poolExecutor.shutdown();
            } catch (Exception e) {
            }
        }));
    }
}